package com.zjitc.service.impl;

import com.zjitc.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Map;

/**
 * 邮件服务实现类
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            logger.info("简单邮件已发送至 {}", to);
        } catch (Exception e) {
            logger.error("发送简单邮件时发生错误: {}", e.getMessage(), e);
        }
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("HTML邮件已发送至 {}", to);
        } catch (MessagingException e) {
            logger.error("发送HTML邮件时发生错误: {}", e.getMessage(), e);
        }
    }

    @Override
    public void sendTemplateEmail(String to, String subject, String templateName, Map<String, Object> variables) {
        try {
            System.out.println("\n===== 开始处理邮件模板 =====");
            System.out.println("模板名称: " + templateName);
            
            // 创建Thymeleaf上下文
            Context context = new Context();
            if (variables != null) {
                System.out.println("设置模板变量: " + variables);
                variables.forEach((key, value) -> {
                    System.out.println("设置变量: " + key + " = " + value);
                    context.setVariable(key, value);
                });
            } else {
                System.out.println("警告: 模板变量为空!");
            }
            
            // 处理模板
            System.out.println("开始处理模板...");
            String emailContent = templateEngine.process(templateName, context);
            
            // 验证处理结果
            if (emailContent == null || emailContent.trim().isEmpty()) {
                System.out.println("错误: 处理模板后内容为空!");
                throw new RuntimeException("处理模板后内容为空");
            }
            
            System.out.println("模板处理结果 (前200字符): " + emailContent.substring(0, Math.min(emailContent.length(), 200)) + "...");
            
            // 发送HTML邮件
            sendHtmlEmail(to, subject, emailContent);
            logger.info("模板邮件[{}]已发送至 {}", templateName, to);
        } catch (Exception e) {
            System.out.println("模板邮件处理或发送时出错: " + e.getMessage());
            e.printStackTrace();
            logger.error("模板邮件处理失败: {}", e.getMessage(), e);
            throw new RuntimeException("模板邮件处理失败: " + e.getMessage(), e);
        }
    }
} 